package com.hnucm.cooklife.ui.fragment;

import android.Manifest;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.ColorUtils;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.amrdeveloper.reactbutton.ReactButton;
import com.amrdeveloper.reactbutton.Reaction;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.hnucm.cooklife.R;
import com.hnucm.cooklife.adapter.CollectAdapter;
import com.hnucm.cooklife.adapter.MyDishAdapter;
import com.hnucm.cooklife.adapter.RecomAdapter;
import com.hnucm.cooklife.base.BaseFragment;
import com.hnucm.cooklife.base.BasePresenter;
import com.hnucm.cooklife.base.Utils;
import com.hnucm.cooklife.base.utils.FbReactions;
import com.hnucm.cooklife.base.utils.LoginUtils;
import com.hnucm.cooklife.bean.db.User;
import com.hnucm.cooklife.bean.me.DishColl;
import com.hnucm.cooklife.contract.user.Contract;
import com.hnucm.cooklife.presenter.me.UserPresenter;
import com.hnucm.cooklife.ui.activity.BGAPhotoPickerActivity;
import com.hnucm.cooklife.ui.activity.DishDetailActivity;
import com.hnucm.cooklife.ui.activity.LoginActivity;
import com.hnucm.cooklife.ui.activity.MomentListActivity;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.widget.QMUICollapsingTopBarLayout;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

import static com.blankj.utilcode.util.ColorUtils.getColor;

public class MeFragment extends BaseFragment<Contract.IUserView, UserPresenter> implements Contract.IUserView,
        com.scwang.smartrefresh.layout.listener.OnLoadMoreListener,
        com.scwang.smartrefresh.layout.listener.OnRefreshListener
{
    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        mPresenter.loadRealMyDish(LoginUtils.getLoginId());
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPresenter.loadRealMyDish(LoginUtils.getLoginId());
    }

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mSmartRefreshLayout;


    private static final String TAG = "MeFragment";
    public static final int RESULT_OK  = -1;
    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int PRC_PHOTO_PICKER = 1;


    public static final int RC_CHOOSE_HEADER = 3;
    public static final int RC_CHOOSE_BG = 4;


    private static final int RC_PHOTO_PREVIEW = 2;

    private static final String EXTRA_MOMENT = "EXTRA_MOMENT";


//    @BindView(R.id.reactbutton)
//    ReactButton mReactButton;

    private int mCurTab;
//
//    @BindView(R.id.topbar_layout)
//    QMUICollapsingTopBarLayout mTopBarLayout;

//    @BindView(R.id.topbar)
//    QMUITopBar mTopBar;



//    @BindView(R.id.me_tab)
//    QMUITabSegment mTab;
//
//    @BindView(R.id.me_viewpager)
//    ViewPager mViewPager;

    @BindView(R.id.me_name)
    TextView mMeName;

    @BindView(R.id.me_header)
    ImageView mHeader;

    @BindView(R.id.bg)
    ImageView mBg;

    @BindView(R.id.real_recycler)
    RecyclerView mRecyclerView;

    private Context mContext;

    private int userid;

    private List<DishColl> mDishCollList = new ArrayList<>();

    private MyDishAdapter mAdapter;

//    private List<String> mTabNames = new ArrayList<>();

//    private ArrayList<Fragment> mFragmentArrayList = new ArrayList<>();

    public static MeFragment getInstance(){
        MeFragment meFragment = new MeFragment();
        return meFragment;
    }

    @Override
    protected UserPresenter createPresenter() {
        return new UserPresenter();
    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoadingFailed() {

    }

    @Override
    public void onLoadSuccess() {
        mSmartRefreshLayout.finishLoadMore();
        mSmartRefreshLayout.finishRefresh();

    }

    @Override
    public void onLoadUser(User user) {
        mMeName.setText(user.username);
        Glide.with(mContext)
                .load(user.icon)
                .fitCenter()
                .centerCrop()
                .into(mHeader);
        Glide.with(mContext)
                .load(user.bg)
                .fitCenter()
                .centerCrop()
                .into(mBg);
    }

    @Override
    public void onRefreshUser(User user) {

    }


    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void alterHeader(){
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");

            Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(mContext)
//                        .cameraFileDir(mTakePhotoCb.isChecked() ? takePhotoDir : null) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
//                        .maxChooseCount(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择张数的最大值
                    .selectedPhotos(null) // 当前已选中的图片路径集合
                    .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                    .build();
            startActivityForResult(photoPickerIntent, RC_CHOOSE_HEADER);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片\n\n2.拍照", PRC_PHOTO_PICKER, perms);
        }
    }


    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void alterBg(){
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
            if (EasyPermissions.hasPermissions(mContext, perms)) {
                // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
                File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");

                Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(mContext)
//                        .cameraFileDir(mTakePhotoCb.isChecked() ? takePhotoDir : null) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
//                        .maxChooseCount(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择张数的最大值
                        .selectedPhotos(null) // 当前已选中的图片路径集合
                        .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                        .build();
                startActivityForResult(photoPickerIntent, RC_CHOOSE_BG);
            } else {
                EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片\n\n2.拍照", PRC_PHOTO_PICKER, perms);
            }
        }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_BG) {
                List<String> selectedPhotos = BGAPhotoPickerActivity.getSelectedPhotos(data);
                File file = new File(selectedPhotos.get(0));

//                Bitmap bitmap = BitmapFactory.decodeFile(file.getName());
//                Bitmap roundBitmap = toRoundBitmap(bitmap);
//                File roundFile = getFile(roundBitmap);

                RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/"), file);
                MultipartBody.Part photo = MultipartBody.Part.createFormData("uploadFile", file.getName(), photoRequestBody);
                mPresenter.updateBg(photo,LoginUtils.getLoginId());

            }
            else if(resultCode == RESULT_OK && requestCode == RC_CHOOSE_HEADER){
                List<String> selectedPhotos = BGAPhotoPickerActivity.getSelectedPhotos(data);
                File file = new File(selectedPhotos.get(0));
                RequestBody photoRequestBody = RequestBody.create(MediaType.parse("image/"), file);
                MultipartBody.Part photo = MultipartBody.Part.createFormData("uploadFile", file.getName(), photoRequestBody);
                mPresenter.updateIcon(photo,LoginUtils.getLoginId());
            }
        }



    //在这里抽取了一个方法   可以封装到自己的工具类中...
    public File getFile(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        File file = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            InputStream is = new ByteArrayInputStream(baos.toByteArray());
            int x = 0;
            byte[] b = new byte[1024 * 100];
            while ((x = is.read(b)) != -1) {
                fos.write(b, 0, x);
            }
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }


    @Override
    protected int getContentViewId() {
        return R.layout.me_fragment;
    }


    @OnClick(R.id.me_header)
//    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void click(){
        new QMUIBottomSheet.BottomListSheetBuilder(getActivity())
                .addItem(R.drawable.menu_me,"更改头像" ,"")
                .addItem(R.drawable.menu_collect,"更改封面图","")
                .setAddCancelBtn(true)
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                        if(position == 0){
                            alterHeader();
                        } else if(position == 1){
                            alterBg();
                        }
                        dialog.dismiss();
                    }
                })
                .build().show();
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        if(!LoginUtils.isLogin()){
            Intent intent = new Intent(mContext, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        getActivity().getWindow().setStatusBarColor(Utils.getColor(mContext));
        setHasOptionsMenu(true);
        return view;
    }


    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.me_toolbar_menu,menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.top_set){
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void init() {
        mContext = getActivity().getApplicationContext();

        mPresenter.loadUser(LoginUtils.getLoginId());
        initStatusBar();
        userid = LoginUtils.getLoginId();
        initAdapter();
        mPresenter.loadRealMyDish(userid);

//        mCurTab = 0;
//        initFragment();
//        intiViewPager();
    }

    private void initAdapter() {
//        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
//        mRecyclerView.setLayoutManager(manager);
//        mAdapter = new CollectAdapter(mContext,mDishCollList);
//        mRecyclerView.setAdapter(mAdapter);

        GridLayoutManager manager = new GridLayoutManager(mContext, 2);
        mRecyclerView.setLayoutManager(manager);
        mAdapter = new MyDishAdapter(mContext,mDishCollList);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new MyDishAdapter.onItemClickListener() {
            @Override
            public void onSeleClickListener(View view, int position) {
                Intent intent = new Intent(getActivity(), DishDetailActivity.class);
                intent.putExtra("dishId",mDishCollList.get(position).dishId);
                DishColl dish = mDishCollList.get(position);

                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }

    private void initStatusBar() {
        getActivity().getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getActivity().getWindow().setStatusBarColor(Color.TRANSPARENT);
        if (ColorUtils.calculateLuminance(getColor(R.color.white)) >= 0.5) {
            getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }

    @Override
    public void onLoadRealMyDish(List<DishColl> dishCollList) {

        mDishCollList.clear();
        mDishCollList.addAll(dishCollList);
        mAdapter.setDishCollList(mDishCollList);
    }

    @Override
    public void onRefreshRealMyDish(List<DishColl> dishCollList) {

    }
//    private void initFragment() {
//        mTabNames.add(0,"菜谱");
//        mTabNames.add(1,"作品");
//        mFragmentArrayList.add(0,new RealDishFragment());
//        mFragmentArrayList.add(1,new RecomFragment());
//    }
//
//    private void intiViewPager() {
//        mViewPager.setAdapter(new FragmentStatePagerAdapter(getChildFragmentManager()) {
//            @NonNull
//            @Override
//            public Fragment getItem(int position) {
//                return mFragmentArrayList.get(position);
//            }
//
//            @Override
//            public int getCount() {
//                return mFragmentArrayList == null ? 0: mFragmentArrayList.size();
//            }
//
//            @Nullable
//            @Override
//            public CharSequence getPageTitle(int position) {
//                return mTabNames.get(position);
//            }
//        });
//
//        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                mCurTab = position;
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });
//        mTab.setupWithViewPager(mViewPager);
//    }


    public Bitmap toRoundBitmap(Bitmap bitmap) {

        // 这里可能需要调整一下图片的大小来让你的图片能在圆里面充分显示
        bitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
        // 构建一个位图对象，画布绘制出来的图片将会绘制到此bitmap对象上
        Bitmap bm = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
        // 构建一个画布,
        Canvas canvas = new Canvas(bm);
        // 获得一个画笔对象，并设置为抗锯齿
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // 获得一种渲染方式对象
        // BitmapShader的作用是使用一张位图作为纹理来对某一区域进行填充。
        // 可以想象成在一块区域内铺瓷砖，只是这里的瓷砖是一张张位图而已。
        Shader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        // 设置画笔的渲染方式
        paint.setShader(shader);
        // 通过画布的画圆方法将渲染后的图片绘制出来
        canvas.drawCircle(100, 100, 100, paint);
        // 返回的就是一个圆形的bitmap对象
        return bm;
    }
}
